# coding=utf-8

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from openpolitics.models import Person, Deputy, Position, Term, DataType, Institution, InstitutionType
from openpolitics.utils import party_affiliation
from django.utils.datastructures import SortedDict

from django.db.models import Q
import pydot
import string

def index(request,
          template_name='openpolitics/browser'):
    '''
    Entry page
    '''
    return render_to_response('%s/index.html' % template_name)

def search(request,
          template_name='openpolitics/browser'):
    query = request.GET.get('query','')
    people = Deputy.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query))
    if people.count() == 1 and people[0].last_name.lower() == query.lower():
        return HttpResponseRedirect('/person/%s' % people[0].slug)
    institutions = Institution.objects.filter(Q(name__icontains=query) | Q(shortname__icontains=query))
    if institutions.count() == 1 and institutions[0].name.lower() == query.lower():
        return HttpResponseRedirect('/institution/%s' % institutions[0].slug)    
    return render_to_response('%s/search.html' % template_name, {
        'people': people,
        'institutions': institutions,
        'query': query,
    })

def people(request,
           template_name='openpolitics/browser'):
    letter = request.GET.get('letter', 'A')
    if letter == 'all':
        pol = Deputy.objects.all()
    else:
        pol = Deputy.objects.filter(last_name__istartswith=letter)
    letters = u'aąbcćdeęfghijklłmnńoóprsśtuwyzźż'.upper()
    list = SortedDict()
    for po in pol:
        letter = po.last_name[0].upper()
        if letter not in list:
            list[letter]=[]
        list[letter].append(po)
    
    return render_to_response('%s/people.html' % template_name, {
        'list': list,
        'letters': letters,
    })

def institutions(request,
                 template_name='openpolitics/browser'):
    iol = Institution.objects.all()
    letters = string.ascii_uppercase
    list = [(letter, iol.filter(name__startswith=letter).order_by('name')) for letter in letters]
    return render_to_response('%s/institutions.html' % template_name, {
        'list': list,
    })

def person(request, slug,
          template_name='openpolitics/browser'):
    person = Deputy.objects.get(slug=slug)
    return render_to_response('%s/person.html' % template_name, {
        'object': person,
    })

def institution(request, slug,
                template_name='openpolitics/browser'):
    institution = Institution.objects.get(slug=slug)
    members = Person.objects.filter(positions__institution=institution)
    return render_to_response('%s/institution.html' % template_name, {
        'object': institution,
        'members': members,
    })

def structure(request,
          template_name='openpolitics/browser'):
    return render_to_response('%s/structure.html' % template_name, {
    })

def _get_positions(inst, name, m):
    names=[]
    pairs=[]
    pos = Position.objects.filter(institution=inst)
    for i in pos:
        cname = '%s%s' % (name,m)
        names.append((cname, i.name.encode('utf-8')))
        pairs.append((name, cname))
        m+=1
    return names, pairs

def _get_children(inst, name):
    names=[]
    pairs=[]
    m=0
    for i in inst.children.all():
        if i.type.name=='Party':
            continue
        cname = '%s%s' % (name,m)
        names.append((cname, i.name.encode('utf-8')))
        pairs.append((name, cname))
        n,p = _get_children(i, cname)
        names.extend(n)
        pairs.extend(p)
        m+=1
    n,p = _get_positions(inst, name, 20)
    names.extend(n)
    pairs.extend(p)
    return names, pairs

def structure_graph(request,
          template_name='openpolitics/browser'):
    '''
    Example view that presents a structure of legislature
    '''
    parl = Institution.objects.get(type__name='State', name='Rzeczpospolita Polska')

    names = [('n0', parl.name.encode('utf-8'))]
    pairs = []

    n,p = _get_children(parl, 'n0')
    names.extend(n)
    pairs.extend(p)

    test = "digraph G {%s;%s}" % ((';'.join(['%s [label="%s"]' % i for i in names])),
                                  (';'.join(['->'.join(i) for i in pairs])))
    data = pydot.graph_from_dot_data(test)
    response = HttpResponse(mimetype="image/png",
                            content=data.create_png())
    return response
